package cn.good.yan.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * 配置
 * # 启动 java 后面 +  -Dreactor.netty.http.server.accessLogEnabled-true （开启日志）
 *
 * @author shengren.yan
 * @create 2024/3/20
 */
@Configuration
public class CorsConfig {

    // 该配置适用于reactive响应式环境
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*"); // 允许method
        config.addAllowedOrigin("*"); // 允许来源
        config.addAllowedHeader("*"); // 允许的请求头参数

        // springboot升级成2.4.0以上时对AllowedOrigin设置发生了改变，不能有”*“,可以替换成AllowedOriginPattern
        // config.addAllowedOriginPattern("*");
        config.setAllowCredentials(true);

        // 必须是reactive包下的UrlBasedCorsConfigurationSource
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }

    // 网关的流控
//    import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
//    import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
//    import org.springframework.web.reactive.function.server.ServerResponse;
//    import org.springframework.web.server.ServerWebExchange;
//    import org.springframework.web.util.pattern.PathPatternParser;
//    /**
//     * 初始化 - 自定义返回信息
//     * # 也可以通过yml进行配置
//     * cloud:
//     * sentinel:
//     * transport:
//     * dashboard: localhost:8080
//     * port: 8719
//     * # 限流的异常的返回信息
//     * scg:
//     * fallback:
//     * mode: response
//     * response-body: "{code:100,messages:'异常'}"
//     * response-status: 600
//     */
//    @PostConstruct
//    public void init() {
//        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
//            @Override
//            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
//                // com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException 异常是流控
//                System.out.println(throwable.toString());
//                return ServerResponse.status(HttpStatus.OK)
//                        .contentType(MediaType.APPLICATION_JSON)
//                        .body(BodyInserters.fromValue("降级l"));
//            }
//        };
//        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
//    }


}
